# -*- coding: utf-8 -*-

'''
/**
 * @addtogroup mpu_alog_watch
 * mpu_alog_watch
 * @{
 */
/**
 * @file        mpu_alog_watch.py
 * @brief       XXXX
 * @note        XXXX
 * @author      靳普诏(puzhao.jin@hopechart.com)
 * @date        2023/05/09
 * @version     1.0

 * @par         修改日志
 * <table>
 * <tr><th>Date         <th>Version     <th>Author      <th> Description
 * <tr><td>2023/05/09   <td>1.0         <td>靳普诏       <td> 创建初始版本
 * @copyright   xxxx
 */
'''

import sys
import os
import datetime
import time

## sys.path.append("D:\\HQ_WorkFolder\\my_tools\\script-tools\\com_watch")

from pyazlib.SpcSerial import SpcSerial

import serial.tools.list_ports

def ClearConsole():
    command = 'clear'
    if os.name in ('nt', 'dos'):  # If Machine is running on Windows, use cls
        command = 'cls'
    os.system(command)

def NoneFilter(data:str):
    result = True

    return result    


class TSerialWatchLive:
    def __init__(self, name = "LIVE",
                 port = "COM1",
                 baudrate = 115200,
                 timeout = 0.05,
                 default_encode = 'utf-8',
                 log_filename = ''):
        self.name = name
        self.port = port
        self.baudrate = baudrate
        self.timeout = timeout
        self.default_encode = default_encode
        self.log_filename = log_filename

        self.__err_existed = False
        return

    def __del__(self):

        return

    def Execute(self, live_scan_inteval = 0.005, dev_scan_inteval = 5, DoFilter = NoneFilter):

        pending = 0
        while True:
            try:
                uart_1 = SpcSerial(name=self.name, port=self.port, baudrate=self.baudrate, timeout=self.timeout)
                pending = 1
                uart_1.Open()
                self.__err_existed = False
                # ClearConsole()
                try:
                    if self.log_filename != '':
                        log_file = open(self.log_filename, 'a', encoding="utf-8")

                    while (True):
                        string_list = uart_1.Read_StrList(10, encode="utf-8")

                        for item in string_list:
                            if DoFilter(item):
                                print(item, end='')
                                if self.log_filename != '':
                                    log_file.write(item)
                finally:
                    if self.log_filename != '':
                        log_file.close()
                    pass
                    time.sleep(live_scan_inteval)

            except serial.SerialException as err:
                if not self.__err_existed:
                    print(f"{datetime.datetime.now().strftime('%H:%M:%S')} exception: {err.args[0]}")
                    self.__err_existed = True

                if pending > 0:
                    uart_1.__del__()
                    pending = 0

            time.sleep(dev_scan_inteval)

        return




#focus = ['HJ', 'bsc_netlink', "Kyee"]
focus = []

def AlogFilter(item:str):
    global focus
    
    if len(focus) < 1:
        result = True
    else:
        result = False
        
        for i in focus:
            if i in item:
                result = True
                break
    return result


if __name__ == "__main__":
    ## 获取当前脚本所在的目录
    SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
    # 输出目录路径
    print("SCRIPT_DIR: "+ SCRIPT_DIR)

    ## 获取脚本传参
    argv = sys.argv
    argc = len(argv)
 
        
    default_com_port = "COM4"
    default_baud = 921600
    log_file = ""
    
    for flag in argv[1:]:
        if "--COM" in flag:
            default_com_port = flag[2:]
            print(f"port:{default_com_port}")
        elif "--BAUD" in flag:
            default_baud = eval(flag[6:])
            print(f"baud:{default_baud}")
        elif "--LOG_FILE=" in flag:
            log_file = flag[11:]
            print(f"baud:{log_file}")
        else:
            focus.append(flag)
    print(focus)
    print(len(focus))
    
    # 打印命令行参数
    for i in range(1, argc):
        print("参数", i, ":", argv[i])
        
    print("============= BIGEN: mpu_alog_watch.py =============")
    
    while True:
        alog = TSerialWatchLive(name = "LIVE", port = default_com_port, baudrate = default_baud, timeout = 0.05, default_encode = 'utf-8', log_filename = log_file)
        try:
            alog.Execute(0.005, 3, AlogFilter)
        except:
            print(" ============== reopen ============= ");

    print("============= END: mpu_alog_watch.py =============")



## Generated on "2023-05-09 20:36:44" by the tool "gen_hq_file.py >> V20230509_1" 
